package com.ruoyi.voucher.service.impl;

import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.Summary;
import com.ruoyi.voucher.domain.Examine;
import com.ruoyi.voucher.domain.Voucher;
import com.ruoyi.voucher.domain.VoucherWord;
import com.ruoyi.voucher.domain.dto.VoucherImportDTO;
import com.ruoyi.voucher.mapper.VoucherMapper;
import com.ruoyi.voucher.service.IVoucherService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @description:
 * @author: qk
 * @create: 2025-02-27 16:54
 **/
@Service
public class IVoucherServiceImpl implements IVoucherService {
    @Autowired
    private VoucherMapper voucherMapper;

    @Override
    public List<Voucher> selectVoucherList(Voucher voucher) {
        return  voucherMapper.selectVoucherList(voucher);
    }




    @Override
    public Voucher selectVoucherByVoucherId(Long voucherId) {
        return voucherMapper.selectVoucherByVoucherId(voucherId);
    }

    @Override
    public int insertVoucher(Voucher voucher) {
        return voucherMapper.insertVoucher(voucher);
    }

    @Override
    public int updateVoucher(Voucher voucher) {
        return voucherMapper.updateVoucher(voucher);
    }

    @Override
    public int deleteVoucherByVoucherIds(Long[] voucherIds) {
        return  voucherMapper.deleteVoucherByVoucherIds(voucherIds);
    }

    @Override
    public int insertExamine(Examine examine) {
        return voucherMapper.inExamine(examine);


    }

    @Override
    public List<VoucherWord> getList() {
        return voucherMapper.getList();
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public String importVoucher(List<VoucherImportDTO> voucherList, String username) {
        if (StringUtils.isNull(voucherList) || voucherList.isEmpty()) {
            throw new ServiceException("导入凭证数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();

        for (VoucherImportDTO voucherDTO : voucherList) {
            try {
                // 数据校验
                validateVoucherData(voucherDTO);

                // 检查凭证字号是否重复
                Voucher existVoucher = new Voucher();
                existVoucher.setVoucherNo(voucherDTO.getVoucherNo());
                List<Voucher> existList = voucherMapper.selectVoucherList(existVoucher);
                if (!existList.isEmpty()) {
                    failureNum++;
                    failureMsg.append("<br/>第 ").append(failureNum)
                            .append(" 条数据导入失败：凭证字号已存在");
                    continue;
                }

                // 转换并补充数据
                Voucher voucher = convertToVoucher(voucherDTO, username);

                // 保存数据
                if (voucherMapper.insertVoucher(voucher) > 0) {
                    successNum++;
                    successMsg.append("<br/>第 ").append(successNum)
                            .append(" 条数据导入成功");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>第 " + (successNum + failureNum) + " 条数据导入失败：";
                failureMsg.append(msg).append(e.getMessage());
            }
        }

        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条");
        }
        return successMsg.toString();
    }

    /**
     * 验证导入凭证数据
     */
    private void validateVoucherData(VoucherImportDTO voucherDTO) {
        if (StringUtils.isEmpty(voucherDTO.getVoucherNo())) {
            throw new ServiceException("凭证字号不能为空");
        }

        if (voucherDTO.getTotalAmount() == null) {
            throw new ServiceException("合计金额不能为空");
        }
        if (voucherDTO.getAccountId() == null) {
            throw new ServiceException("账套ID不能为空");
        }
        if (voucherDTO.getWordId() == null) {
            throw new ServiceException("凭证字ID不能为空");
        }
    }

    /**
     * 将导入DTO转换为实体对象
     */
    private Voucher convertToVoucher(VoucherImportDTO voucherDTO, String username) {
        Voucher voucher = new Voucher();
        BeanUtils.copyProperties(voucherDTO, voucher);

        // 设置默认值
        Date now = DateUtils.getNowDate();
        voucher.setCreator(username);
        voucher.setCreateTime(now);
        voucher.setAccountPeriod("1");
        voucher.setModifier(username);
        voucher.setModifyTime(now);
        voucher.setAuditStatus("未审核");
        voucher.setIsVoid(1);
        voucher.setIsDeleted(0);
        voucher.setVersion(1L);
        voucher.setRemainingAmount(voucherDTO.getTotalAmount());

        return voucher;
    }
}
